package com.egao.orderB.biz.impl;

import com.egao.common.core.damon.constant.UserConstant;
import com.egao.common.core.damon.results.BaseDao;
import com.egao.common.core.damon.results.PageResult2;
import com.egao.common.core.damon.utils.PinyinUtils;
import com.egao.common.core.damon.utils.Utils;
import com.egao.common.core.web.JsonResult;
import com.egao.common.system.entity.User;
import com.egao.orderB.biz.AddressFactoryBiz;
import com.egao.orderB.entity.AddressFactory;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * 数据层实现类
 * @author : Doman
 * @date : 2020-08-07 09:56:44
 * @version ：1.0
 */
@Repository
public class AddressFactoryBizImpl extends BaseDao implements AddressFactoryBiz {

	@Override
	public JsonResult list(PageResult2<T> page, AddressFactory addressFactory, User loginUser) throws Exception {
		Map<String, String> map  = new HashMap<String, String>();
		RowMapper<AddressFactory> rm = new BeanPropertyRowMapper<AddressFactory>(AddressFactory.class);
		StringBuffer sql = new StringBuffer("select a.id,a.organization_id,a.address_id,a.bill_id");
        sql.append(",a.customer_id,a.faddress,a.fphone,a.fstate,a.fremark");
        sql.append(",a.longitude,a.latitude,a.radius,a.pinyin");
		sql.append(",a.create_time,a.create_user,a.update_time,a.update_user");
        sql.append(",sogzn.organization_name organizationName,suser.username createName ");
        sql.append(" from chf_address_factory a ");
        sql.append(" inner join sys_user suser on suser.user_id=a.create_user ");
        sql.append(" inner join sys_organization sogzn on sogzn.organization_id=a.organization_id ");
        sql.append(" where a.deleted=0 and sogzn.deleted=0 ");
		if(loginUser.getUserId() != UserConstant.ADMIN_ID){
            sql.append(" and a.organization_id=:tableOrganizationId ");
            map.put("tableOrganizationId", loginUser.getOrganizationId() + "");
        }
    	if(Utils.isNotEmpty(addressFactory)){
			if(Utils.isNotEmpty(addressFactory.getAddressId())){
				sql.append(" and a.address_id=:address_id ");
				map.put("address_id", addressFactory.getAddressId());
			}
			if(Utils.isNotEmpty(addressFactory.getBillId())){
				sql.append(" and a.bill_id=:bill_id ");
				map.put("bill_id", addressFactory.getBillId());
			}
			if(Utils.isNotEmpty(addressFactory.getFaddress())){
				sql.append(" and (instr(a.faddress,:faddress)>0 or instr(a.pinyin,:faddress)>0) ");
				map.put("faddress", addressFactory.getFaddress());
			}
			if(Utils.isNotEmpty(addressFactory.getSort())&&Utils.isNotEmpty(addressFactory.getOrder())){
                sql.append(" order by a."+addressFactory.getSort()+" "+addressFactory.getOrder());
            } else {
                sql.append(" order by a.fstate desc");
            }
		}
		return jsonResult(getPageQueryList(page, sql.toString(), map, rm));
	}

	@Override
	public List<AddressFactory> list(AddressFactory addressFactory, User loginUser) {
		Map<String, String> map  = new HashMap<String, String>();
		RowMapper<AddressFactory> rm = new BeanPropertyRowMapper<AddressFactory>(AddressFactory.class);
        StringBuffer sql = new StringBuffer("select a.id,a.organization_id,a.address_id,a.bill_id");
        sql.append(",a.customer_id,a.faddress,a.fphone,a.fstate,a.fremark");
		sql.append(",a.longitude,a.latitude,a.radius,a.pinyin");
		sql.append(",a.create_time,a.create_user,a.update_time,a.update_user");
        sql.append(",sogzn.organization_name organizationName,suser.username createName ");
        sql.append(" from chf_address_factory a ");
        sql.append(" inner join sys_user suser on suser.user_id=a.create_user ");
        sql.append(" inner join sys_organization sogzn on sogzn.organization_id=a.organization_id ");
        sql.append(" where a.deleted=0 and sogzn.deleted=0 ");
		if(loginUser.getUserId() != UserConstant.ADMIN_ID){
            sql.append(" and a.organization_id=:tableOrganizationId ");
            map.put("tableOrganizationId", loginUser.getOrganizationId() + "");
        }
    	if(Utils.isNotEmpty(addressFactory)){
			if(Utils.isNotEmpty(addressFactory.getAddressId())){
				sql.append(" and a.address_id=:address_id ");
				map.put("address_id", addressFactory.getAddressId());
			}
			if(Utils.isNotEmpty(addressFactory.getBillId())){
				sql.append(" and a.bill_id=:bill_id ");
				map.put("bill_id", addressFactory.getBillId());
			}
			if(Utils.isNotEmpty(addressFactory.getIds())){
				sql.append(" and a.id in (:ids) ");
				map.put("ids", addressFactory.getIds());
			}
			if(Utils.isNotEmpty(addressFactory.getFaddress())){
				sql.append(" and (instr(a.faddress,:faddress)>0 or instr(a.pinyin,:faddress)>0) ");
				map.put("faddress", addressFactory.getFaddress());
			}
            if(Utils.isNotEmpty(addressFactory.getSort())&&Utils.isNotEmpty(addressFactory.getOrder())){
				sql.append(" order by a."+addressFactory.getSort()+" "+addressFactory.getOrder());
			} else {
				sql.append(" order by a.fstate desc");
			}
		}
		getMapParameter(sql, map);
		return jdbcTemplate.query(sql.toString(),map, rm);
	}

	@Override
	public AddressFactory getById(AddressFactory addressFactory) {
		RowMapper<AddressFactory> rm = new BeanPropertyRowMapper<AddressFactory>(AddressFactory.class);
		Map<String, String> map  = new HashMap<String, String>();
		StringBuffer sql = new StringBuffer("select a.id,a.organization_id,a.address_id,a.bill_id");
        sql.append(",a.customer_id,a.faddress,a.fphone,a.fstate,a.fremark");
		sql.append(",a.longitude,a.latitude,a.radius,a.pinyin");
		sql.append(",a.create_time,a.create_user,a.update_time,a.update_user");
        sql.append(",sogzn.organization_name organizationName,suser.username createName ");
        sql.append(" from chf_address_factory a ");
        sql.append(" inner join sys_user suser on suser.user_id=a.create_user ");
        sql.append(" inner join sys_organization sogzn on sogzn.organization_id=a.organization_id ");
        sql.append(" where a.deleted=0 and sogzn.deleted=0 and a.id=:id ");
		map.put("id", addressFactory.getId());
		getMapParameter(sql, map);
		return jdbcTemplate.queryForObject(sql.toString(), map, rm);
	}

	@Override
	public Integer save(AddressFactory addressFactory, User loginUser) {
		GeneratedKeyHolder generatedKeyHolder = new GeneratedKeyHolder();
		KeyHolder keyHolder=new GeneratedKeyHolder();
		addressFactory.setPinyin(PinyinUtils.ToFirstChar(addressFactory.getFaddress()));
		Map<String, String> map  = new HashMap<String, String>();
		StringBuffer sql =new StringBuffer("insert into chf_address_factory (");
        sql.append("organization_id,address_id,bill_id,faddress,fphone");
        sql.append(",customer_id,longitude,latitude,radius,pinyin");
		sql.append(",fstate,fremark,create_user,create_time) values ( ");
        sql.append(":organization_id,:address_id,:bill_id,:faddress,:fphone");
		sql.append(",:customer_id,:longitude,:latitude,:radius,:pinyin");
		sql.append(",:fstate,:fremark,:create_user,now())");
        map.put("organization_id", loginUser.getOrganizationId() + "");
        map.put("bill_id", addressFactory.getBillId());
        map.put("address_id", addressFactory.getAddressId());
		map.put("faddress", addressFactory.getFaddress());
		map.put("fphone", addressFactory.getFphone());
		map.put("fstate", addressFactory.getFstate());
		map.put("customer_id", addressFactory.getCustomerId());
		map.put("longitude", addressFactory.getLongitude());
		map.put("latitude", addressFactory.getLatitude());
		map.put("radius", addressFactory.getRadius());
		map.put("pinyin", addressFactory.getPinyin());
		map.put("fremark", addressFactory.getFremark());
		map.put("create_user", loginUser.getUserId() + "");
		getMapParameter(sql, map);
		//		System.err.println("受到影响的行数=" + retVal + ",
		int retVal = this.jdbcTemplate.update(sql.toString(), new SqlParameterSource() {
			@Override
			public boolean hasValue(String paramName) {
				return map.containsKey(paramName);
			}
			@Override
			public Object getValue(String paramName) throws IllegalArgumentException {
				return map.get(paramName);
			}
		}, generatedKeyHolder);
		Integer id = generatedKeyHolder.getKey().intValue();
		return id;
	}

	@Override
	public boolean updateFstate(AddressFactory addressFactory, User loginUser) {
		Map<String, String> map  = new HashMap<String, String>();
		StringBuffer sql =new StringBuffer("update chf_address_factory set ");
		sql.append(" fstate='' ");
		sql.append("  where bill_id=:address_id ");
		map.put("address_id", addressFactory.getAddressId());
		int count = jdbcTemplate.update(sql.toString(), map);

		map  = new HashMap<String, String>();
		sql =new StringBuffer("update chf_address_factory set ");
        sql.append("fstate='默认' ");
		sql.append(",update_time=now() ");
		sql.append(",update_user=:update_user where id=:id ");
		map.put("update_user", loginUser.getUserId() + "");
		map.put("id", addressFactory.getId());
		getMapParameter(sql, map);
		count = jdbcTemplate.update(sql.toString(), map);
		return count > 0;
	}

	@Override
	public boolean update(AddressFactory addressFactory, User loginUser) {
		addressFactory.setPinyin(PinyinUtils.ToFirstChar(addressFactory.getFaddress()));
		Map<String, String> map  = new HashMap<String, String>();
		StringBuffer sql =new StringBuffer("update chf_address_factory set ");
        sql.append("faddress=:faddress,fphone=:fphone ");
		sql.append(",longitude=:longitude,latitude=:latitude,radius=:radius,pinyin=:pinyin");
		sql.append(",update_time=now() ");
		sql.append(",update_user=:update_user where id=:id ");
        map.put("faddress", addressFactory.getFaddress());
        map.put("fphone", addressFactory.getFphone());
        map.put("longitude", addressFactory.getLongitude());
        map.put("latitude", addressFactory.getLatitude());
        map.put("radius", addressFactory.getRadius());
        map.put("pinyin", addressFactory.getPinyin());
		map.put("update_user", loginUser.getUserId() + "");
		map.put("id", addressFactory.getId());
		getMapParameter(sql, map);
		int count = jdbcTemplate.update(sql.toString(), map);
		return count > 0;
	}

	@Override
	public boolean remove(AddressFactory addressFactory, User loginUser) {
		int count = 0;
		Map<String, String> map = null;
		if(addressFactory.getId().length()>0){
			for(String ID : addressFactory.getId().split(",")){
				map  = new HashMap<String, String>();
				if(ID==null || ID.equals("")){ break; }
				StringBuffer sql =new StringBuffer("update chf_address_factory set deleted=1" +
						",update_user=:update_user, update_time=now() "
						+ " where id =:id ");
				map.put("update_user", loginUser.getUserId() + "");
				map.put("id", ID);
				getMapParameter(sql, map);
				count = jdbcTemplate.update(sql.toString(),map);
			}
		}
		return count > 0;
	}
}
